package controller;

import java.io.IOException;
import java.util.ArrayList;

import DAO.CookingDAO;
import DAO.DishDAO;
import DTO.CookingDTO;
import DTO.DishDTO;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import constants.StringConstants;

/**
 * Servlet implementation class DishServlet
 */
public class DishServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String EDIT_DISH_PAGE = "admin/dish-edit.jsp";
	private static final String DISH_LIST_PAGE = "admin/dish.jsp";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DishServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession().getAttribute("ADMIN_USERNAME") != null) {
			DishDAO dishDao = new DishDAO();
			ArrayList<DishDTO> dishList = new ArrayList<DishDTO>();
			dishList = dishDao.select();

			CookingDAO cookingDao = new CookingDAO();
			for (DishDTO dishDTO : dishList) {
				CookingDTO ck = dishDTO.getCooking();
				cookingDao.get(ck);
			}

			request.setAttribute("DISHLIST", dishList);
			RequestDispatcher rd = request.getRequestDispatcher(DISH_LIST_PAGE);
			rd.forward(request, response);
		} else {
			RequestDispatcher rd = request
					.getRequestDispatcher("admin/admin-login.html");
			rd.forward(request, response);
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession().getAttribute("ADMIN_USERNAME") != null) {
			String action = request.getParameter("action");
			if (action.equals(StringConstants.EDIT)) {
				int id = Integer.parseInt(request.getParameter("id"));
				DishDAO dishDao = new DishDAO();
				DishDTO dish = new DishDTO();
				dish.setId(id);
				dishDao.get(dish);

				CookingDAO cookingDao = new CookingDAO();
				ArrayList<CookingDTO> list = cookingDao.select();

				request.setAttribute("COOKINGLIST", list);
				request.setAttribute("DISHDTO", dish);
				RequestDispatcher rd = request
						.getRequestDispatcher(EDIT_DISH_PAGE);
				rd.forward(request, response);
			}
		} else {
			RequestDispatcher rd = request
					.getRequestDispatcher("admin/admin-login.html");
			rd.forward(request, response);
		}

	}
}
